import {Component, OnInit} from '@angular/core';
import {FormControl, FormGroup, Validators} from "@angular/forms";
import {RoleUser} from "../../../basic-data/role/entity/role-user";
import {NzMessageService} from "ng-zorro-antd/message";
import {ActivatedRoute} from "@angular/router";
import {SystemInfoService} from "../../../basic-data/system-info/service/system-info.service";
import {RoleInfoService} from "../../../basic-data/role/service/role-info.service";
import {BarnSystemInfo} from "../../../basic-data/system-info/entity/barn-system-info";
import {concatMap} from "rxjs/operators";
import {ProjectService} from "../service/project.service";

@Component({
  selector: 'app-project-edit',
  templateUrl: './project-edit.component.html',
  styleUrls: ['./project-edit.component.less']
})
export class ProjectEditComponent implements OnInit {

  remarkMaxLength = 1000
  validateForm = new FormGroup({
    projectName: new FormControl(null, [Validators.required, Validators.maxLength(20)]),
    remark: new FormControl(null, [Validators.maxLength(this.remarkMaxLength)]),
    pid: new FormControl(null),
    enable: new FormControl("1", [Validators.maxLength(20)])
  })

  loading = false
  isVisible = false
  filter: string = ''

  // 全部
  users: RoleUser[] = [];
  // 弹出窗选择的
  dialogSelectedUser: RoleUser[] = [];
  // 服务器已经保存的
  hadUsers: RoleUser[] = []

  constructor(private projectService: ProjectService, private msg: NzMessageService, private routeInfo: ActivatedRoute, private systemInfoService: SystemInfoService,
              private roleInfoService: RoleInfoService) {
  }

  ngOnInit(): void {
    const pid = this.routeInfo.snapshot.queryParams["pid"];
    if (pid) {
      this.loading = true
      this.projectService.getById(pid).subscribe(value => {
        if (value) {
          this.validateForm.patchValue(value);
          this.getHadUser(pid)
        }
      }, () => this.loading = false, () => this.loading = false)
    }
    this.getProjectManagers()
  }

  submitForm() {

    if (this.validateForm.valid) {
      const team = this.validateForm.getRawValue();
      this.loading = true
      this.projectService.save(team).subscribe(value => {
        this.validateForm.patchValue(value)
        this.loading = false
        this.msg.success("保存成功")
      }, error => this.loading = false);
    } else {
      for (const i in this.validateForm.controls) {
        this.validateForm.controls[i].markAsDirty();
        this.validateForm.controls[i].updateValueAndValidity();
      }
    }
  }

  // 查询所有产品管理人员
  getProjectManagers() {
    this.systemInfoService.getById(BarnSystemInfo.PROJECT_MANAGER_ROLE_ID).pipe(
      concatMap(v => {
        return this.roleInfoService.getUsers({roleId: v?.variableValue, isInclude: '1'} as RoleUser)
      })
    ).subscribe(value => {
      this.users = value.data
    })
  }

  handleOk() {
    this.isVisible = false
    // 向服务器保存，然后重新查询
    this.loading = true
    const pid = this.validateForm.get('pid').value;
    const userIds = this.dialogSelectedUser.map(value => value.userId)
    this.projectService.addUsers(pid, userIds)
      .subscribe(() => {
        this.loading = false
        this.msg.success("保存成功")
        this.getHadUser(this.validateForm.get('pid').value)
      }, () => this.loading = false)
    this.dialogSelectedUser = []
  }

  clickRow(user: RoleUser) {
    const old = this.dialogSelectedUser.findIndex(value => value.userId === user.userId);
    if (old < 0) {
      this.dialogSelectedUser.push(user)
    } else {
      this.dialogSelectedUser.splice(old, 1)
    }
  }

  getHadUser(projectId: string) {
    this.loading = true
    this.projectService.getUsers(projectId).subscribe(value => {
      this.loading = false
      this.hadUsers = value
    }, () => this.loading = false)
  }

  get pid() {
    return this.validateForm.get('pid').value
  }

  get computedUsers() {
    let target = this.users;
    if (this.hadUsers && this.hadUsers.length) {
      target = this.users.filter(value => {
        return !this.hadUsers.find(v => value.userId === v.userId)
      });
    }
    if (!target || !target.length) {
      return []
    }
    if (!this.filter) {
      return target;
    } else {
      return target.filter(value => value.userName.indexOf(this.filter) > -1 || value.userAccount.indexOf(this.filter) > -1);
    }
  }

  isSelected(userId: string) {
    return !!this.dialogSelectedUser.find(value => value.userId === userId);

  }

  deleteUser(userId: string) {
    const projectId = this.pid;
    this.loading = true
    this.projectService.deleteUser(projectId, userId).subscribe(() => {
      this.msg.success("删除成功");
      this.loading = false
      this.getHadUser(projectId)
    }, () => this.loading = false)
  }
}
